package com.farm.iproject.controller;

import com.farm.iproject.domain.Dictype;
import com.farm.iproject.domain.Field;
import com.farm.iproject.domain.Project;
import com.farm.iproject.service.DictypeServiceInter;
import com.farm.iproject.service.FieldServiceInter;
import com.farm.iproject.service.ProjectServiceInter;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;

import com.farm.web.easyui.EasyUiTreeNode;
import com.farm.web.easyui.EasyUiTreeNodeHandle;
import com.farm.web.easyui.EasyUiUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.ResultsHandle;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：字典类型控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/dictype")
@Controller
public class DictypeController extends WebUtils {
	private final static Logger log = Logger.getLogger(DictypeController.class);
	@Resource
	private DictypeServiceInter dicTypeServiceImpl;
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private FieldServiceInter fieldServiceImpl;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(String projectid, DataQuery query, HttpServletRequest request) {
		try {
			query.addDefaultSort(new DBSort("SORT", "ASC"));
			query = EasyUiUtils.formatGridQuery(request, query);
			query.addRule(new DBRule("projectid", projectid, "="));
			if (query.getRule("PARENTID") == null) {
				query.addRule(new DBRule("PARENTID", "NONE", "="));
			}
			DataResult result = dicTypeServiceImpl.createDictypeSimpleQuery(query).search();
			result.runDictionary("1:结果启用,2:条件/结果", "ABLETYPE");
			result.runDictionary("1:完全匹配,2:匹配子集", "LIKETYPE");
			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					Dictype supertype = dicTypeServiceImpl.getDictypeEntity((String) row.get("SUPERID"));
					row.put("SUPERNAME", supertype.getName());
				}
			});
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 字典树
	 */
	@RequestMapping("/dictypeTree")
	@ResponseBody
	public Object loadTreeNode(String projectid, String id) {
		try {
			List<EasyUiTreeNode> allnodes = null;
			if (id == null) {
				// 如果是未传入id，就是根节点，就构造一个虚拟的上级节点
				id = "NONE";
				List<EasyUiTreeNode> list = new ArrayList<>();
				EasyUiTreeNode nodes = new EasyUiTreeNode("NONE", "检索字典", "open", "icon-address");
				nodes.setChildren(
						EasyUiTreeNode
								.formatAsyncAjaxTree(
										EasyUiTreeNode
												.queryTreeNodeOne(id, "SORT", "WSCH_P_DICTYPE", "ID", "PARENTID",
														"NAME", "CTIME", " and projectid='" + projectid + "'")
												.getResultList(),
										EasyUiTreeNode
												.queryTreeNodeTow(id, "SORT", "WSCH_P_DICTYPE", "ID", "PARENTID",
														"NAME", "CTIME", " and a.projectid='" + projectid + "'")
												.getResultList(),
										"PARENTID", "ID", "NAME", "CTIME"));
				list.add(nodes);
				allnodes = list;
			} else {
				allnodes = EasyUiTreeNode.formatAsyncAjaxTree(
						EasyUiTreeNode.queryTreeNodeOne(id, "SORT", "WSCH_P_DICTYPE", "ID", "PARENTID", "NAME", "CTIME",
								" and projectid='" + projectid + "'").getResultList(),
						EasyUiTreeNode.queryTreeNodeTow(id, "SORT", "WSCH_P_DICTYPE", "ID", "PARENTID", "NAME", "CTIME",
								" and a.projectid='" + projectid + "'").getResultList(),
						"PARENTID", "ID", "NAME", "CTIME");
			}
			EasyUiUtils.runTreeNodeHandle(allnodes, new EasyUiTreeNodeHandle() {
				@Override
				public void handle(EasyUiTreeNode node) {
					Dictype type = dicTypeServiceImpl.getDictypeEntity(node.getId());
					if (type != null && type.getParentid().equals("NONE")) {
						node.setIconCls("icon-consulting");
					}
				}
			});
			return allnodes;
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(Dictype entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = dicTypeServiceImpl.editDictypeEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(Dictype entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = dicTypeServiceImpl.insertDictypeEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				dicTypeServiceImpl.deleteDictypeEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(String projectid, HttpSession session) {
		Project project = projectServiceImpl.getProjectEntity(projectid);
		return ViewMode.getInstance().putAttr("project", project).putAttr("projectid", projectid)
				.returnModelAndView("iproject/DictypeResult");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(String projectid, String parentid, RequestMode pageset, String ids) {
		try {
			ViewMode view = ViewMode.getInstance();
			if (StringUtils.isNotBlank(ids)) {
				Dictype entity = dicTypeServiceImpl.getDictypeEntity(ids);
				projectid = entity.getProjectid();
				view.putAttr("entity", entity);
				if (!entity.getParentid().equals("NONE")) {
					parentid = entity.getParentid();
				}
			}
			if (StringUtils.isNotBlank(projectid)) {
				Project project = projectServiceImpl.getProjectEntity(projectid);
				view.putAttr("project", project);
				List<Field> fields = fieldServiceImpl.getFields(projectid);
				view.putAttr("fields", fields);
			}
			if (StringUtils.isNotBlank(parentid)) {
				Dictype parent = dicTypeServiceImpl.getDictypeEntity(parentid);
				view.putAttr("parent", parent);
			}
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				return view.putAttr("pageset", pageset).returnModelAndView("iproject/DictypeForm");
			}
			case (1): {// 新增
				return view.putAttr("pageset", pageset).returnModelAndView("iproject/DictypeForm");
			}
			case (2): {// 修改
				return view.putAttr("pageset", pageset).returnModelAndView("iproject/DictypeForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("iproject/DictypeForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("iproject/DictypeForm");
		}
	}
}
